package net.cctms.zhishu.webAppFramework.gestureImage;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.support.annotation.NonNull;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.drawable.GlideDrawable;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.target.Target;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.listener.SimpleImageLoadingListener;

import net.cctms.zhishu.R;
import net.cctms.zhishu.webAppFramework.gestureImage.view.gestureimage.GestureController;
import net.cctms.zhishu.webAppFramework.gestureImage.view.gestureimage.Settings;
import net.cctms.zhishu.webAppFramework.gestureImage.view.gestureimage.views.GestureImageView;
import net.cctms.zhishu.webAppFramework.gestureImage.view.gestureimage.views.interfaces.GestureView;
import net.cctms.zhishu.webAppFramework.gestureImage.view.gestureimage.views.utils.RecyclePagerAdapter;
import net.cctms.zhishu.webAppFramework.material.MaterialProgressWheel;
import net.cctms.zhishu.webAppFramework.model.PicEntity;
import net.cctms.zhishu.webAppFramework.utils.BitmapUtils;
import net.cctms.zhishu.webAppFramework.utils.FileUtil;
import net.cctms.zhishu.webAppFramework.utils.GlideUtil;
import net.cctms.zhishu.webAppFramework.utils.Log;
import net.cctms.zhishu.webAppFramework.utils.MD5;
import net.cctms.zhishu.webAppFramework.utils.StorageUtil;
import net.cctms.zhishu.webAppFramework.utils.ToastUtil;
import net.cctms.zhishu.webAppFramework.utils.UrlUtil;

import java.io.File;
import java.lang.reflect.Type;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

public class GestureImagesAdapter extends RecyclePagerAdapter<GestureImagesAdapter.ViewHolder> {
    private ArrayList<PicEntity> picEntityList;
    private final ViewPager mViewPager;
    private Context context;
    private int pageFrom;

    public GestureImagesAdapter(Context context, ViewPager pager, ArrayList<PicEntity> picEntityList, int pageFrom) {
        this.context = context;
        mViewPager = pager;
        this.picEntityList = picEntityList;
        this.pageFrom = pageFrom;
       /* GsonBuilder gb = new GsonBuilder();
        gb.disableHtmlEscaping();
        Gson gson = gb.create();
        Type type = new TypeToken<ArrayList<PicEntity>>() {}.getType();
        this.picEntityList = gson.fromJson(gson.toJson(picEntityList), type);*/
    }

    @Override
    public int getCount() {
        return picEntityList.size();
    }

    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup container) {

        View view = LayoutInflater.from(context).inflate(R.layout.browse_pictrue_view, container, false);
        ViewHolder holder = new ViewHolder(view);
        holder.gestureImageView.getController().enableScrollInViewPager(mViewPager);
        return holder;
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        setupGestureView(holder.gestureImageView);

        PicEntity entity = picEntityList.get(position);
        holder.gestureImageView.getController().resetState();
        holder.progressView.setVisibility(View.VISIBLE);
        holder.gestureImageView.setImageResource(R.drawable.browse_pictrue_trans);
        holder.gestureImageView.getController().setLongPressEnabled(false); //取消长按下载
        holder.loadFailLayout.setVisibility(View.GONE);
        Log.i("GestureImagesAdapter originalPicUrl --->  " + entity.originalPicUrl);
        // 获取链接后缀用于处理gif图片
        String postfix = UrlUtil.getUrlPostfix(entity.originalPicUrl);
        //  判断是否是Gif图片，Gif图片不再加载原图
        if (postfix != null && postfix.equalsIgnoreCase("gif")) {
            loadGif(holder, entity, false);
        } else {
            loadPicture(holder, entity, false);
        }
    }


    /**
     * 加载Gif
     *
     * @param holder
     * @param entity
     */
    private void loadGif(final ViewHolder holder, final PicEntity entity, boolean isReload) {
        if (isReload) {
            holder.progressView.setVisibility(View.VISIBLE);
            holder.loadFailLayout.setVisibility(View.GONE);
        }

        GlideUtil.loadGif(context, entity.originalPicUrl, holder.gestureImageView, new RequestListener<String, GlideDrawable>() {
            @Override
            public boolean onException(Exception e, String s, Target<GlideDrawable> target, boolean b) {
                Log.i("loadGif ---> onException");
                holder.progressView.setVisibility(View.GONE);
                holder.loadFailLayout.setVisibility(View.VISIBLE);
                holder.reloadPicture.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        loadGif(holder, entity, true);
                    }
                });
                return true;
            }

            @Override
            public boolean onResourceReady(GlideDrawable glideDrawable, String s, Target<GlideDrawable> target, boolean b, boolean b1) {
                Log.i("loadGif ---> onResourceReady");
                holder.progressView.setVisibility(View.GONE);
                holder.loadFailLayout.setVisibility(View.GONE);
                holder.gestureImageView.getController().setLongPressEnabled(true);
                handleLongPress(holder.gestureImageView, entity.originalPicUrl, SAVE_TYPE.PICTURE);
                return false;
            }
        });
    }

    /**
     * 加载图片
     *
     * @param holder
     * @param entity
     */
    public void loadPicture(final ViewHolder holder, final PicEntity entity, boolean isReload) {
        if (isReload) {
            holder.progressView.setVisibility(View.VISIBLE);
            holder.loadFailLayout.setVisibility(View.GONE);
        }

        Log.i("GestureImagesAdapter  -- start download the btmap --->  " + entity.originalPicUrl);
        GlideUtil.downloadBitmap(context, entity.originalPicUrl, new SimpleImageLoadingListener() {
            @Override
            public void onLoadingStarted(String s, View view) {
                Log.i("GestureImagesAdapter  -- onLoadingStarted --->  " + s);
            }

            @Override
            public void onLoadingFailed(String s, View view, FailReason failReason) {

                Log.i("GestureImagesAdapter  -- onLoadingFailed --->  ");

                holder.progressView.setVisibility(View.GONE);
                holder.loadFailLayout.setVisibility(View.VISIBLE);
                holder.reloadPicture.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {

                        loadPicture(holder, entity, true);
                    }
                });
            }

            @Override
            public void onLoadingComplete(String s, View view, Bitmap bitmap) {

                Log.i("GestureImagesAdapter  -- onLoadingComplete --->  " + bitmap);

                holder.progressView.setVisibility(View.GONE);
                if (bitmap != null) {
                    holder.loadFailLayout.setVisibility(View.GONE);
                    //处理长按下载
                    holder.gestureImageView.getController().setLongPressEnabled(true);
                    handleLongPress(holder.gestureImageView, entity.originalPicUrl, SAVE_TYPE.PICTURE);

                    if (bitmap.getWidth() > 2 * 1080 || bitmap.getHeight() > 2 * 1920) {
                        bitmap = BitmapUtils.comp(bitmap, 1920, 2 * 1080);
                        holder.gestureImageView.setImageBitmap(bitmap);
                    } else {
                        holder.gestureImageView.setImageBitmap(bitmap);
                    }
                    //holder.gestureImageView.setScaleType(ImageView.ScaleType.FIT_XY);
                } else {
                    holder.loadFailLayout.setVisibility(View.VISIBLE);
                    holder.reloadPicture.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            loadPicture(holder, entity, true);
                        }
                    });
                }
            }

            @Override
            public void onLoadingCancelled(String s, View view) {

            }
        });


//                GlideUtil.downloadBitmap(context, entity.originalPicUrl, new SimpleTarget<Bitmap>() {
//                    @Override
//                    public void onLoadFailed(Exception e, Drawable errorDrawable) {
//                        super.onLoadFailed(e, errorDrawable);
//                        Log.i("downloadBitmap  -- onLoadFailed  " + e);
//                        holder.progressView.setVisibility(View.GONE);
//                        holder.loadFailLayout.setVisibility(View.VISIBLE);
//                        holder.reloadPicture.setOnClickListener(new View.OnClickListener() {
//                            @Override
//                            public void onClick(View view) {
//
//                                loadPicture(holder, entity, true);
//                            }
//                        });
//                    }
//
//                    @Override
//                    public void onResourceReady(Bitmap bitmap, GlideAnimation<? super Bitmap> glideAnimation) {
//                        Log.i("GestureImagesAdapter  -- onResourceReady  " + bitmap);
//                        holder.progressView.setVisibility(View.GONE);
//                        if (bitmap != null) {
//                            holder.loadFailLayout.setVisibility(View.GONE);
//                            //处理长按下载
//                            holder.gestureImageView.getController().setLongPressEnabled(true);
//                            handleLongPress(holder.gestureImageView, entity.originalPicUrl, SAVE_TYPE.PICTURE);
//
//                            if (bitmap.getWidth() > 2 * 1080 || bitmap.getHeight() > 2 * 1920) {
//                                bitmap = BitmapUtils.comp(bitmap, 1920, 2 * 1080);
//                                holder.gestureImageView.setImageBitmap(bitmap);
//                            } else {
//                                holder.gestureImageView.setImageBitmap(bitmap);
//                            }
//                        } else {
//                            holder.loadFailLayout.setVisibility(View.VISIBLE);
//                            holder.reloadPicture.setOnClickListener(new View.OnClickListener() {
//                                @Override
//                                public void onClick(View view) {
//                                    loadPicture(holder, entity, true);
//                                }
//                            });
//                        }
//                    }
//                });
    }

    public enum SAVE_TYPE {
        GIF, PICTURE
    }

    private void handleLongPress(GestureImageView gestureImageView, final String originalPicUrl, final SAVE_TYPE Type) {
        gestureImageView.getController().setOnGesturesListener(new GestureController.OnGestureListener() {
            @Override
            public void onDown(MotionEvent e) {

            }

            @Override
            public boolean onSingleTapUp(MotionEvent e) {
                return false;
            }

            @Override
            public boolean onSingleTapConfirmed(MotionEvent e) {
                return false;
            }

            @Override
            public void onLongPress(MotionEvent e) {
                new AlertDialog.Builder(context, R.style.AlertDialogStyle)
                        .setItems(new String[]{"保存到手机", "取消"}, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.cancel();
                                switch (which) {
                                    case 0:
                                        saveImage(Type, originalPicUrl);
                                        break;
                                    case 1:
                                        break;
                                }
                            }
                        }).show();
            }

            @Override
            public boolean onDoubleTap(MotionEvent e) {
                return false;
            }
        });

    }

    /**
     * 保存图片，有缓存从缓存中取图片，没有从网上下载
     *
     * @param originalPicUrl
     */
    public void saveImage(final SAVE_TYPE Type, final String originalPicUrl) {
        if (TextUtils.isEmpty(originalPicUrl)) {
            ToastUtil.showShortToast(context, "保存失败");
            return;
        }
        Glide.with(context).load(originalPicUrl).downloadOnly(new SimpleTarget<File>() {
            @Override
            public void onResourceReady(File resource, GlideAnimation<? super File> glideAnimation) {
                if (resource == null) {
                    ToastUtil.showShortToast(context, "保存失败");
                    return;
                }
                String fileName = UrlUtil.getImageFileName(originalPicUrl);
                if (fileName == null) {
                    String suffix = (Type == SAVE_TYPE.GIF ? ".gif" : ".jpeg");
                    fileName = MD5.crypt(originalPicUrl).concat(suffix);
                }
                File imageFile = FileUtil.createPictrueFile(fileName);
                if (imageFile != null) {
                    FileUtil.copyFile(resource.getAbsolutePath(), imageFile.getAbsolutePath());

                    // 最后通知图库更新
                    Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
                    Uri uri = Uri.fromFile(imageFile);
                    intent.setData(uri);
                    context.sendBroadcast(intent);

                    ToastUtil.showLongToast(context, "图片已保存到" + StorageUtil.getDownloadImageDir());
                }
            }

            @Override
            public void onLoadFailed(Exception e, Drawable errorDrawable) {
                super.onLoadFailed(e, errorDrawable);
                ToastUtil.showShortToast(context, "保存失败");
            }
        });
    }

    private void setupGestureView(GestureView view) {
        view.getController().getSettings()
                .setPanEnabled(true)
                .setZoomEnabled(true)
                .setDoubleTapEnabled(true)
                .setFillViewport(false)
                .setFitMethod(Settings.Fit.INSIDE)    // OUTSIDE短边与屏幕匹配(长的显示到外面去了)  INSIDE 场边匹配，短边有黑色填充    。。。。   总结（长图用OUSIDE，普通用INSIDE）
                .setGravity(Gravity.CENTER);
    }


    static class ViewHolder extends RecyclePagerAdapter.ViewHolder {

        public GestureImageView gestureImageView;
        public MaterialProgressWheel progressView;
        public LinearLayout loadFailLayout;
        public TextView reloadPicture;

        public ViewHolder(View view) {
            super(view);
            gestureImageView = (GestureImageView) view.findViewById(R.id.gestureImageView);
            progressView = (MaterialProgressWheel) view.findViewById(R.id.progressView);
            loadFailLayout = (LinearLayout) view.findViewById(R.id.loadFailLayout);
            reloadPicture = (TextView) view.findViewById(R.id.reloadPicture);
        }
    }
}
